<template>
  <div class="major-tree-chart">
    <CommonChart ref="commonChartRef" :options="chartOptions" height="100%" @my-click="handleClick" />
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, ref, watch } from "vue"
import type { EChartsOption } from "echarts"
import { CommonChart } from "./index"

const props = defineProps<{
  data: any[]
  active: boolean
  curFirstMajor: string
  currentMajor: string
}>()
const emits = defineEmits(["update:currentMajor"])

const currentMajor = computed({
  get: () => props.currentMajor,
  set: val => {
    emits("update:currentMajor", val)
  }
})

const commonChartRef = ref<InstanceType<typeof CommonChart>>()
// 将树形数据转换为ECharts树图所需的格式
// 将树形数据转换为ECharts树图所需的格式
const convertData = (data: any[], curFirstMajor: string) => {
  const convert = (item: any) => {
    return {
      name: item.title,
      level: item.level,
      children: item.children ? item.children.map(convert) : []
    }
  }

  const foundItem = data.find(item => {
    return item.title === curFirstMajor
  })
  return foundItem ? [convert(foundItem)] : []
}

// 图表配置
const chartOptions = computed<EChartsOption>(() => ({
  tooltip: {
    trigger: "item",
    triggerOn: "mousemove"
  },
  series: [
    {
      type: "tree",
      data: convertData(props.data, props.curFirstMajor),
      top: "5%",
      left: "15%",
      bottom: "5%",
      right: "15%",
      symbolSize: 7,
      layout: "orthogonal",
      orient: "horizontal",
      initialTreeDepth: 2,
      label: {
        position: "top",
        distance: 15,
        rotate: 0,
        verticalAlign: "middle",
        align: "center",
        fontSize: 12,
        color: "#333"
      },
      leaves: {
        label: {
          position: "right",
          distance: 5,
          verticalAlign: "middle",
          align: "left",
          fontSize: 8,
          color: "#333"
        }
      },
      itemStyle: {
        color: "#4CAF50",
        borderColor: "#4CAF50"
      },
      lineStyle: {
        color: "#999",
        width: 1,
        curveness: 0.5
      },
      emphasis: {
        focus: "descendant"
      },
      expandAndCollapse: true,
      animationDuration: 550,
      animationDurationUpdate: 750
    }
  ]
}))

// 增加 resize 防抖
const handleResize = () => {
  if (!props.active) return
  nextTick(() => {
    commonChartRef.value?.resize()
  })
}

const handleClick = (params: any) => {
  if (params.data.level === "level3") {
    currentMajor.value = params.data.name
  }
}

// 监听激活状态变化
watch(
  () => props.active,
  isActive => {
    if (isActive) handleResize()
  }
)
</script>

<style lang="scss" scoped>
.major-tree-chart {
  width: 100%;
  height: 100%;
}
</style>
